Difference Between localStorage and sessionStorage in JavaScript

localStorage and sessionStorage are two types of web storage that allow you to store data in a web browser. Both are part of the HTML5 Web Storage API, but they differ in their lifespan and scope.

1. localStorage

localStorage allows you to store data with no expiration time. The data will persist even after the browser is closed and reopened, making it useful for storing information that should be available across sessions.


// Storing data in localStorage
localStorage.setItem("username", "JohnDoe");

// Retrieving data from localStorage
let username = localStorage.getItem("username");
console.log(username);  // Output: JohnDoe
    

Note: The data stored in localStorage does not expire and is available until explicitly deleted.

2. sessionStorage

sessionStorage is used to store data for the duration of the page session. The data is available as long as the browser tab remains open. Once the tab is closed, the data is cleared.


// Storing data in sessionStorage
sessionStorage.setItem("sessionID", "12345");

// Retrieving data from sessionStorage
let sessionID = sessionStorage.getItem("sessionID");
console.log(sessionID);  // Output: 12345
    

Note: The data stored in sessionStorage is only available for the duration of the page session and is cleared once the tab is closed.

3. Key Differences

Feature localStorage sessionStorage
Data Persistence Persists even after the browser is closed. Data is cleared once the tab or browser is closed.
Scope Accessible across all windows/tabs in the same browser. Accessible only in the same window/tab during the session.
Data Capacity Typically 5MB per domain. Typically 5MB per domain (same as localStorage).

4. When to Use

Conclusion

localStorage and sessionStorage are both essential tools in modern web development, allowing you to store data in the browser. Understanding their differences will help you choose the right one based on your needs—whether you need persistent data storage or session-specific data storage.